//
//  NoAttentionDetailViewController.m
//  SouthChina
//
//  Created by Mr.Y on 14/11/7.
//  Copyright (c) 2014年 科创. All rights reserved.
//

#import "PublicInforDetailViewController.h"
#import "PublicAccountDao.h"
#import "MessageSessionDao.h"
#import "MessageListViewController.h"
@interface PublicInforDetailViewController ()<UIAlertViewDelegate,UIActionSheetDelegate>
@property(strong, nonatomic) UISwitch *groupSwitchBtn;

@end

@implementation PublicInforDetailViewController
@synthesize publicaccount;
@synthesize sessionId;
@synthesize publicType;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    [self addTitleBarWithBackBtn:publicaccount.appName needReturn:YES];
    
    //图像
    UIImageView * headImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10+TITLE_BAR_HEGIHT+(YNEW), 60, 60)];
    [headImage setBackgroundColor:[UIColor colorWithRed:236/255.0f green:235/255.0f blue:243/255.0f alpha:1]];
     NSURL *url= [NSURL URLWithString: [publicaccount.headImg hasPrefix:@"http"]?publicaccount.headImg:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,publicaccount.headImg]];
    [headImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    [self.view addSubview:headImage];
    
    //名称
    CGSize appNameContentSize = [publicaccount.appName sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:CGSizeMake(180, CGFLOAT_MAX)lineBreakMode:NSLineBreakByWordWrapping];
    UILabel * nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(22+headImage.frame.size.width,5+TITLE_BAR_HEGIHT+(YNEW), appNameContentSize.width, 30)];
    nameLabel.text = publicaccount.appName;
    nameLabel.font = [UIFont systemFontOfSize:15.0f];
    nameLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:nameLabel];
    
    //官方或者调试中
    BOOL isDebug =[@"1" isEqualToString:[publicaccount getValue:@"debugMode"] ];
    BOOL isOffice =[@"1" isEqualToString:[publicaccount getValue:@"isOfficial"]];
    UILabel * officeLabel = [[UILabel alloc] init];
    UILabel * debugLabel = [[UILabel alloc] init];
    if (isOffice) {
        officeLabel.frame = CGRectMake(5+nameLabel.frame.size.width+nameLabel.frame.origin.x,10+TITLE_BAR_HEGIHT+(YNEW),35, 21);
        officeLabel.text = @"官方";
        officeLabel.textColor = [UIColor whiteColor];
        
        officeLabel.font = [UIFont boldSystemFontOfSize:15.0f];
        officeLabel.textAlignment = NSTextAlignmentCenter;
        officeLabel.backgroundColor = [UIColor colorWithRed:0/255.0f green:128/255.0f blue:0/255.0f alpha:1];
        [self.view addSubview:officeLabel];
        
        UIImageView * offcialImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
        offcialImage.image = [UIImage imageNamed:@"offcial.png"];
         [headImage addSubview:offcialImage];
        
    }else if (isDebug)
    {
        debugLabel.frame = CGRectMake(5+nameLabel.frame.size.width+nameLabel.frame.origin.x+officeLabel.frame.size.width+officeLabel.frame.origin.x,10+TITLE_BAR_HEGIHT+(YNEW),50, 21);
        debugLabel.text = @"调试中";
        debugLabel.textColor = [UIColor whiteColor];
        debugLabel.font = [UIFont boldSystemFontOfSize:15.0f];
        debugLabel.textAlignment = NSTextAlignmentCenter;
        debugLabel.backgroundColor = [UIColor colorWithRed:178/255.0f green:34/255.0f blue:34/255.0f alpha:1];
        [self.view addSubview:debugLabel];
    }
    
    //版本（当前版本、更新时间）
    UILabel * version = [[UILabel alloc] initWithFrame:CGRectMake(22+headImage.frame.size.width,22+nameLabel.frame.origin.y, 180, 30)];
    version.text = [NSString stringWithFormat:@"当前版本：%@",[publicaccount getValue:@"appVersion"]];
    [version setTextColor:[UIColor grayColor]];
    version.backgroundColor = [UIColor clearColor];;
    version.font = [UIFont systemFontOfSize:10.0f];
    [self.view addSubview:version];
    
    //更新时间
    UILabel * versiontime = [[UILabel alloc] initWithFrame:CGRectMake(22+headImage.frame.size.width,16+version.frame.origin.y, 180, 30)];
    versiontime.text = [NSString stringWithFormat:@"更新时间：%@",[publicaccount getValue:@"appVersionTime"]];
    [versiontime setTextColor:[UIColor grayColor]];
    versiontime.backgroundColor = [UIColor clearColor];;
    versiontime.font = [UIFont systemFontOfSize:10.0f];
    [self.view addSubview:versiontime];
    
    //分割背景
    UILabel * versionbk = [[UILabel alloc] initWithFrame:CGRectMake(0,35+versiontime.frame.origin.y,self.view.frame.size.width , 20)];
    versionbk.backgroundColor = [UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1];
    [self.view addSubview:versionbk];
    
    //功能介绍
    UILabel * functionLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,headImage.frame.origin.y+headImage.frame.size.height+35, 70, 30)];
    functionLabel.text = @"功能介绍";
    functionLabel.font = [UIFont systemFontOfSize:15.0f];
    functionLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:functionLabel];
    
    //功能详情
    UILabel * detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(15+functionLabel.frame.size.width,headImage.frame.origin.y+headImage.frame.size.height+35, SCREEN_WIDTH-100, 30)];
    detailLabel.numberOfLines = 3;
    detailLabel.text = publicaccount.funcDesc;
    detailLabel.font = [UIFont systemFontOfSize:12.0f];
    detailLabel.backgroundColor = [UIColor clearColor];
    [detailLabel setTextColor:[UIColor grayColor]];
    [self.view addSubview:detailLabel];
    
    //功能背景
    UILabel * functionLabelbk = [[UILabel alloc] initWithFrame:CGRectMake(0,40+functionLabel.frame.origin.y,self.view.frame.size.width , 1)];
    functionLabelbk.backgroundColor = [UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1];
    [self.view addSubview:functionLabelbk];

    //历史消息
    UIButton * messageHistoryBtn = [[UIButton alloc] initWithFrame:CGRectMake(10,15+detailLabel.frame.size.height+detailLabel.frame.origin.y, SCREEN_WIDTH, 40)];
    [messageHistoryBtn addTarget:self action:@selector(messageHistoryBtn:) forControlEvents:UIControlEventTouchUpInside];
    [messageHistoryBtn setTitle:@"" forState:UIControlStateNormal];
    [messageHistoryBtn setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:messageHistoryBtn];
    UILabel * messageHistoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,5, 200, 30)];
    messageHistoryLabel.text = @"查看历史消息";
    messageHistoryLabel.font = [UIFont systemFontOfSize:15.0f];
    [messageHistoryBtn addSubview:messageHistoryLabel];
    
    //关注应用
    UIButton * attentionBtn = [[UIButton alloc] init];
    if ([publicaccount isSubscribeStatus]) {
        //已关注界面
        //历史消息背景
        UILabel * msghistoryLabelbk = [[UILabel alloc] initWithFrame:CGRectMake(0,42+messageHistoryBtn.frame.origin.y,self.view.frame.size.width , 1)];
        msghistoryLabelbk.backgroundColor = [UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1];
        [self.view addSubview:msghistoryLabelbk];
        
        UIButton * receivesMessageBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,10+messageHistoryBtn.frame.size.height+messageHistoryBtn.frame.origin.y, SCREEN_WIDTH, 40)];
        [receivesMessageBtn addTarget:self action:@selector(receivesMessageBtn:) forControlEvents:UIControlEventTouchUpInside];
        [receivesMessageBtn setTitle:@"" forState:UIControlStateNormal];
        [receivesMessageBtn setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:receivesMessageBtn];
        
        _groupSwitchBtn = [[UISwitch alloc] initWithFrame:CGRectMake((SCREEN_WIDTH)-100+(YNEW), 0, 20, 20)];
        if (publicaccount.isReceiveMessage) {
            [_groupSwitchBtn setOn:YES];
        }
        [_groupSwitchBtn addTarget:self action:@selector(chooseBtn1:) forControlEvents:UIControlEventValueChanged];
        [receivesMessageBtn addSubview:_groupSwitchBtn];
        
        UILabel * receivesMessageLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,0, 200, 30)];
        receivesMessageLabel.text = @"接收消息";
        receivesMessageLabel.font = [UIFont systemFontOfSize:15.0f];
        [receivesMessageBtn addSubview:receivesMessageLabel];
        
        //接收消息背景
        UILabel * receivesMsgLabelbk = [[UILabel alloc] initWithFrame:CGRectMake(0,40+receivesMessageBtn.frame.origin.y,self.view.frame.size.width , 20)];
        receivesMsgLabelbk.backgroundColor = [UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1.0];
        [self.view addSubview:receivesMsgLabelbk];
        
        //进入应用
        UIButton * messageBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,10+receivesMsgLabelbk.frame.size.height+receivesMsgLabelbk.frame.origin.y, SCREEN_WIDTH, 35)];
        [messageBtn addTarget:self action:@selector(messageBtn:) forControlEvents:UIControlEventTouchUpInside];
        [messageBtn setTitle:@"" forState:UIControlStateNormal];
        [messageBtn setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:messageBtn];
        
        UILabel * messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,0, 200, 30)];
        messageLabel.text = @"进入应用";
        messageLabel.font = [UIFont systemFontOfSize:15.0f];
        [messageBtn addSubview:messageLabel];
        
        //进入应用背景
        UILabel * messageLabelbk = [[UILabel alloc] initWithFrame:CGRectMake(0,35+messageBtn.frame.origin.y,self.view.frame.size.width , 1)];
        messageLabelbk.backgroundColor = [UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1.0];
        [self.view addSubview:messageLabelbk];
        
        //消息清除
        UIButton * clearMessageBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,5+messageBtn.frame.size.height+messageBtn.frame.origin.y, SCREEN_WIDTH, 35)];
        [clearMessageBtn addTarget:self action:@selector(clearMessageBtn:) forControlEvents:UIControlEventTouchUpInside];
        [clearMessageBtn setTitle:@"" forState:UIControlStateNormal];
        [clearMessageBtn setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:clearMessageBtn];
        
        UILabel * clearMessageLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,0, 200, 30)];
        clearMessageLabel.text = @"清除消息";
        clearMessageLabel.font = [UIFont systemFontOfSize:15.0f];
        [clearMessageBtn addSubview:clearMessageLabel];
        
        //清除消息背景
        UILabel * clearMsgLabelbk = [[UILabel alloc] initWithFrame:CGRectMake(0,40+clearMessageBtn.frame.origin.y,self.view.frame.size.width , 1)];
        clearMsgLabelbk.backgroundColor = [UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1.0];
        [self.view addSubview:clearMsgLabelbk];
        
        //取消关注
        attentionBtn.frame = CGRectMake(10,10+clearMsgLabelbk.frame.origin.y, (SCREEN_WIDTH)-20, 40);
        [attentionBtn setTitle:@"取消关注" forState:UIControlStateNormal];
        [attentionBtn addTarget:self action:@selector(attentionBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        [attentionBtn setBackgroundColor:[UIColor redColor]];
        [self.view addSubview:attentionBtn];

    }else{
        //未关注界面
        //背景
        UILabel * attentionLabelbk = [[UILabel alloc] initWithFrame:CGRectMake(0,60+messageHistoryBtn.frame.origin.y,self.view.frame.size.width , 20)];
        attentionLabelbk.backgroundColor = [UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1];
        [self.view addSubview:attentionLabelbk];
        
        //马上关注
        attentionBtn.frame = CGRectMake(15,20+attentionLabelbk.frame.size.height+attentionLabelbk.frame.origin.y, (SCREEN_WIDTH)-30, 40);
        [attentionBtn setTitle:@"马上关注" forState:UIControlStateNormal];
        [attentionBtn addTarget:self action:@selector(attentionBtn:) forControlEvents:UIControlEventTouchUpInside];
        [attentionBtn setBackgroundColor:[UIColor colorWithRed:0.0f/255.0f green:131.0f/255.0f blue:255.0f/255.0f alpha:1.0f]];
        [self.view addSubview:attentionBtn];
        if (isDebug)
        {
            NSString * str =[publicaccount getValue:@"debugUser"];
            NSArray * arr = [str componentsSeparatedByString:@","];
            NSString *realId = [DE getGlobalVar:LOGIN_USER_REALID];
            bool isInWhimt = NO;
            for (NSString * str in arr ) {
                if ([realId isEqualToString:str]) {
                    isInWhimt = YES;
                    break;
                }
            }
            if (!isInWhimt) {
                attentionBtn.enabled = NO;
                [attentionBtn setTitle:@"应用调试中，不能关注" forState:UIControlStateNormal];
                attentionBtn.layer.masksToBounds = YES;
                attentionBtn.layer.cornerRadius = 5.0;
                UIImage *debugImg=[UIImage imageNamed:@"color_btn_disable.png"];
                debugImg=[debugImg stretchableImageWithLeftCapWidth:20 topCapHeight:20];
                [attentionBtn setBackgroundImage:debugImg forState:UIControlStateNormal];
            }
        }

    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)chooseBtn1:(id)sender{
    BOOL isButtonOn = [_groupSwitchBtn isOn];
    NSString * flag = @"";
    if (isButtonOn) {
         flag = @"1";
        
    }else {
         flag = @"0";
    }
    NSDictionary *params = @{@"publicId":publicaccount.appId,@"userId":DE.userId,@"flag":flag};
    [DE serverCall:@"setMsgReceiveFlag" params:params callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        NSLog(@"%@",data);
        if(success && [data objectForKey:@"result"])
        {
            [publicaccount setPublicIsReceive:isButtonOn];
            
            [PublicAccountDao updatePublicAccount:publicaccount];
            [self showAlerHUD:[flag isEqualToString:@"1"]?@"设置接收成功":@"设置取消接收成功" framewidth:[flag isEqualToString:@"1"]?90:120] ;
        }else
        {
          [self showAlerHUD:[flag isEqualToString:@"1"]?@"设置接收失败":@"设置取消接收失败" framewidth:[flag isEqualToString:@"1"]?90:120] ;
        }
        //1009
        if (publicaccount.isReceiveMessage) {
            [_groupSwitchBtn setOn:YES];
        }
        else
            [_groupSwitchBtn setOn:NO];
    }];
}

//重写提示效果(个性化)
-(void)showAlerHUD:(NSString*)text framewidth:(CGFloat) hudwidth
{
    BDKNotifyHUD * hudex = [[BDKNotifyHUD alloc] initWithImageEX:[UIImage imageNamed:@""]  text:text hudWidth:hudwidth];
    hudex.center = CGPointMake(self.view.center.x,self.view.center.y+202);
    [self.view addSubview:hudex];
    [hudex presentWithDuration:1.0 speed:0.5f inView:self.view completion:^{
        [hudex removeFromSuperview];
    }];
}


-(void)receivesMessageBtn:(id)sender
{
}
-(void)messageBtn:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];

}
-(void)clearMessageBtn:(id)sender
{
    UIActionSheet * sheet = [[UIActionSheet alloc] initWithTitle:@"将清空所有系统和个人的消息记录" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"清除一周前的消息" otherButtonTitles:@"清除一月前的消息",@"清空消息记录", nil];
    sheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSDate *  senddate=[NSDate date];
    NSDate *sevenDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:([senddate timeIntervalSinceReferenceDate] - 7*24*3600)];
    NSDate *mouthDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:([senddate timeIntervalSinceReferenceDate] - 7*24*3600)];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd"];
    NSString *  sevenDateString=[dateformatter stringFromDate:sevenDate];
    NSString *  mouthDateString=[dateformatter stringFromDate:mouthDate];
    
    switch (buttonIndex) {
        case 0:
            [MessageSessionDao deleteMessageByTime:sevenDateString session:sessionId];
            kAppDelegate.needRefrsh = YES;
            [self showAlerHUD:@"清除一周前消息成功！" framewidth:140] ;
            break;
        case 1:
            [MessageSessionDao deleteMessageByTime:mouthDateString session:sessionId];
            kAppDelegate.needRefrsh = YES;
            [self showAlerHUD:@"清除一月前消息成功！" framewidth:140] ;
            break;
        case 2:
            NSLog(@"XXXXXXXXXXXXXXsessionId:%@",sessionId);
            [MessageSessionDao deleteMessageSession:sessionId];
             //20150815 清除message
            [MessageDao deleteMessageBysessionId:sessionId];
            kAppDelegate.needRefrsh = YES;
            [self showAlerHUD:@"清除所有消息成功！" framewidth:140] ;
            //20150928 发消息通知，消息列表才会刷新
            [[NSNotificationCenter defaultCenter] postNotificationName:PUBLIC_ATTENTION_BROADCAST object:nil];
            break;
        default:
            break;
    }
}
-(void)messageHistoryBtn:(id)sender
{
    NSLog(@"查看历史消息");
    HistoryMessageController *hiss = [[HistoryMessageController alloc] init];
    hiss.publicId = publicaccount.appId;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:hiss animated:NO];
    
}
-(void)attentionBtn:(id)sender
{
    NSDictionary *params = @{@"publicId":publicaccount.appId,@"userId":DE.userId};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [DE serverCall:[publicaccount isSubscribeStatus]?@"unsubscribe":@"subscribe" params:params callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"%@",data);
        if(success && [data objectForKey:@"result"])
        {
            if ([publicaccount isSubscribeStatus]) {
                //删除该条会话
                [MessageSessionDao deleteMessageSession:sessionId];
                //20150820 清除message
                [MessageDao deleteMessageBysessionId:sessionId];
            }else{
                
                [publicaccount setPublicIsReceive:YES];
            }
            //20150929如果是取消关注，则同时要置ishome为0
            if([publicaccount isSubscribeStatus])
                [publicaccount setIsHomeApp:NO];
            [publicaccount setPublicSubscribeStatus:![publicaccount isSubscribeStatus]];
            [PublicAccountDao updatePublicAccount:publicaccount];
            //发送通知
            [[NSNotificationCenter defaultCenter] postNotificationName:PUBLIC_ATTENTION_BROADCAST object:nil];
            UIAlertView *aler =  [[UIAlertView alloc] initWithTitle:@"提示" message:[publicaccount isSubscribeStatus]?@"关注成功！":@"取消关注成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [aler show];
        }
        
    }];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:YES];
}



@end
